package com.aizuda.boot.modules.business.contract.service.impl;

import com.aizuda.boot.modules.business.contract.entity.ContractTypeDepartmentEntity;
import com.aizuda.boot.modules.business.contract.entity.dto.ContractTypeCache;
import com.aizuda.boot.modules.business.contract.entity.vo.ContractTypeShowDTO;
import com.aizuda.boot.modules.business.contract.service.ContractTypeDepartmentService;
import com.aizuda.boot.modules.business.contract.service.ContractTypeService;
import com.aizuda.boot.modules.business.contract.entity.ContractTypeEntity;
import com.aizuda.boot.modules.business.performance.mapper.ContractTypeMapper;
import com.aizuda.boot.modules.common.constant.RedisKeyConstant;
import com.aizuda.boot.modules.common.util.RedisService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.Locked;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 合同类型Service实现类
 *
 * @Author sangyirong
 * @Version 1.0
 * @Date 2025/5/20 13:36
 */
@Slf4j
@Service
public class ContractTypeServiceImpl extends ServiceImpl<ContractTypeMapper, ContractTypeEntity> implements ContractTypeService {

    @Resource
    private RedisService redisService;

    @Resource
    private ContractTypeDepartmentService contractTypeDepartmentService;

    @EventListener(ApplicationReadyEvent.class)
    public void cacheContractType() {
        log.info("项目启动成功开始缓存合同类型");
        List<ContractTypeEntity> list = this.list();
        if (CollectionUtils.isEmpty(list)) {
            log.info("没有合同类型,无需缓存");
            return;
        }
        Map<Integer, List<ContractTypeDepartmentEntity>> typeDepartment = contractTypeDepartmentService.list()
                .stream().collect(Collectors.groupingBy(ContractTypeDepartmentEntity::getContractTypeId));
        list.forEach(contractType -> {
            ContractTypeCache contractTypeCache = new ContractTypeCache();
            BeanUtils.copyProperties(contractType, contractTypeCache);
            List<ContractTypeDepartmentEntity> department = typeDepartment.get(contractType.getId());
            if (!CollectionUtils.isEmpty(department)) {
                contractTypeCache.setDepartmentIds(department.stream().map(ContractTypeDepartmentEntity::getDepartmentId).toList());
            }
            redisService.setHashObject(RedisKeyConstant.Business.CONTRACT_TYPE_PREFIX + contractType.getId(), contractTypeCache);
        });
        log.info("项目启动成功缓存合同类型完成,共缓存合同类型: {} 个", list.size());
    }
} 